package com.zyp.jobseeker.service.impl;

import com.zyp.jobseeker.service.InterviewService;
import com.zyp.jobseeker.mapper.InterviewMapper;
import com.zyp.jobseeker.entity.Interview;
import com.zyp.jobseeker.enums.InterviewStatus;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zyp
 * @version 1.0
 */
@Service
public class InterviewServiceImpl implements InterviewService {

    private static final Logger logger = LoggerFactory.getLogger(InterviewServiceImpl.class);

    @Autowired
    private InterviewMapper interviewMapper;

    /**
     * 企业主动邀请学生面试
     */
    @Override
    public Map<String, Object> createInterviewInvitation(Interview interview) {
        logger.info("[面试邀请] 收到企业主动邀请请求，参数: {}", interview);

        try {
            // 设置面试状态为待确认
            interview.setStatus(InterviewStatus.PENDING_CONFIRM);
            interview.setInviteTime(new java.util.Date());

            // 插入面试邀请记录
            int rowsAffected = interviewMapper.createInterviewInvitation(interview);

            if (rowsAffected > 0) {
                logger.info("[面试邀请] 企业主动邀请成功，面试ID: {}", interview.getId());
                
                // 构建返回结果
                Map<String, Object> result = new HashMap<>();
                result.put("id", interview.getId());
                result.put("applicationId", null);
                result.put("enterpriseId", interview.getEnterpriseId());
                result.put("studentId", interview.getStudentId());
                result.put("positionId", interview.getPositionId());
                result.put("inviteTime", interview.getInviteTime());
                result.put("interviewTime", interview.getInterviewTime());
                result.put("interviewLocation", interview.getInterviewLocation());
                result.put("status", interview.getStatus().name());
                result.put("remark", interview.getRemark());

                return result;
            } else {
                logger.warn("[面试邀请] 企业主动邀请失败");
                return createErrorResult("创建面试邀请失败");
            }
        } catch (Exception e) {
            logger.error("[面试邀请] 企业主动邀请时发生异常", e);
            throw new RuntimeException("创建面试邀请失败: " + e.getMessage());
        }
    }

    /**
     * 查询学生收到的面试邀请
     */
    @Override
    public PageInfo<Map<String, Object>> getInterviewsByStudent(
            Long studentId, Integer status, int page, int size) {
        logger.info("[面试邀请] 收到学生面试邀请查询请求，参数：studentId={}, status={}, page={}, size={}",
                studentId, status, page, size);

        try {
            // 开始分页查询
            PageHelper.startPage(page, size);
            List<Interview> interviews = interviewMapper.findInterviewsByStudentId(studentId, status);

            // 转换为Map结构
            PageInfo<Interview> interviewPageInfo = new PageInfo<>(interviews);
            PageInfo<Map<String, Object>> mapPageInfo = convertToMapPageInfo(interviewPageInfo);

            logger.info("[面试邀请] 学生面试邀请查询完成，返回结果数: {}", mapPageInfo.getTotal());
            return mapPageInfo;
        } catch (Exception e) {
            logger.error("[面试邀请] 查询学生面试邀请失败", e);
            throw new RuntimeException("查询学生面试邀请失败: " + e.getMessage());
        }
    }

    /**
     * 查询企业发出的面试邀请
     */
    @Override
    public PageInfo<Map<String, Object>> getInterviewsByEnterprise(
            Long enterpriseId, Integer status, int page, int size) {
        logger.info("[面试邀请] 收到企业面试邀请查询请求，参数：enterpriseId={}, status={}, page={}, size={}",
                enterpriseId, status, page, size);

        try {
            // 开始分页查询
            PageHelper.startPage(page, size);
            List<Interview> interviews = interviewMapper.findInterviewsByEnterpriseId(enterpriseId, status);

            // 转换为Map结构
            PageInfo<Interview> interviewPageInfo = new PageInfo<>(interviews);
            PageInfo<Map<String, Object>> mapPageInfo = convertToMapPageInfo(interviewPageInfo);

            logger.info("[面试邀请] 企业面试邀请查询完成，返回结果数: {}", mapPageInfo.getTotal());
            return mapPageInfo;
        } catch (Exception e) {
            logger.error("[面试邀请] 查询企业面试邀请失败", e);
            throw new RuntimeException("查询企业面试邀请失败: " + e.getMessage());
        }
    }

    /**
     * 学生接受面试邀请
     */
    @Transactional
    @Override
    public Map<String, Object> acceptInterview(Long id, Long studentId) {
        logger.info("[面试邀请] 收到学生接受邀请请求，参数：id={}, studentId={}", id, studentId);

        try {
            // 验证面试邀请是否存在
            Interview interview = interviewMapper.selectById(id);
            if (interview == null) {
                logger.warn("[面试邀请] 尝试接受不存在的面试邀请，ID: {}", id);
                return createErrorResult("面试邀请不存在");
            }

            // 验证是否为该学生的面试邀请
            if (!interview.getStudentId().equals(studentId)) {
                logger.warn("[面试邀请] 学生尝试接受不属于自己的面试邀请，ID: {}, studentId: {}", id, studentId);
                return createErrorResult("无权操作此面试邀请");
            }

            // 执行接受操作
            int rowsAffected = interviewMapper.acceptInterview(id, studentId);
            if (rowsAffected <= 0) {
                logger.warn("[面试邀请] 接受面试邀请失败，ID: {}", id);
                return createErrorResult("接受面试邀请失败");
            }

            // 重新查询更新后的面试信息
            Interview updatedInterview = interviewMapper.selectById(id);
            if (updatedInterview == null) {
                logger.warn("[面试邀请] 无法获取更新后的面试信息，ID: {}", id);
                return createErrorResult("无法获取更新后的面试信息");
            }

            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("id", updatedInterview.getId());
            result.put("status", updatedInterview.getStatus().name());
            result.put("updateTime", new java.util.Date());

            logger.info("[面试邀请] 学生接受面试邀请成功，ID: {}", id);
            return result;
        } catch (Exception e) {
            logger.error("[面试邀请] 学生接受面试邀请时发生异常", e);
            throw new RuntimeException("接受面试邀请失败: " + e.getMessage());
        }
    }

    /**
     * 学生拒绝面试邀请
     */
    @Transactional
    @Override
    public Map<String, Object> rejectInterview(Long id, Long studentId) {
        logger.info("[面试邀请] 收到学生拒绝邀请请求，参数：id={}, studentId={}", id, studentId);

        try {
            // 验证面试邀请是否存在
            Interview interview = interviewMapper.selectById(id);
            if (interview == null) {
                logger.warn("[面试邀请] 尝试拒绝不存在的面试邀请，ID: {}", id);
                return createErrorResult("面试邀请不存在");
            }

            // 验证是否为该学生的面试邀请
            if (!interview.getStudentId().equals(studentId)) {
                logger.warn("[面试邀请] 学生尝试拒绝不属于自己的面试邀请，ID: {}, studentId: {}", id, studentId);
                return createErrorResult("无权操作此面试邀请");
            }

            // 执行拒绝操作
            int rowsAffected = interviewMapper.rejectInterview(id, studentId);
            if (rowsAffected <= 0) {
                logger.warn("[面试邀请] 拒绝面试邀请失败，ID: {}", id);
                return createErrorResult("拒绝面试邀请失败");
            }

            // 重新查询更新后的面试信息
            Interview updatedInterview = interviewMapper.selectById(id);
            if (updatedInterview == null) {
                logger.warn("[面试邀请] 无法获取更新后的面试信息，ID: {}", id);
                return createErrorResult("无法获取更新后的面试信息");
            }

            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("id", updatedInterview.getId());
            result.put("status", updatedInterview.getStatus().name());
            result.put("updateTime", new java.util.Date());

            logger.info("[面试邀请] 学生拒绝面试邀请成功，ID: {}", id);
            return result;
        } catch (Exception e) {
            logger.error("[面试邀请] 学生拒绝面试邀请时发生异常", e);
            throw new RuntimeException("拒绝面试邀请失败: " + e.getMessage());
        }
    }

    /**
     * 将PageInfo<Interview>转换为PageInfo<Map<String, Object>>
     */
    private PageInfo<Map<String, Object>> convertToMapPageInfo(PageInfo<Interview> interviewPageInfo) {
        // 创建新的PageInfo并转换数据
        PageInfo<Map<String, Object>> mapPageInfo = new PageInfo<>(new ArrayList<>(), interviewPageInfo.getNavigatePages());

        // 复制基础分页信息
        mapPageInfo.setPageNum(interviewPageInfo.getPageNum());
        mapPageInfo.setPageSize(interviewPageInfo.getPageSize());
        mapPageInfo.setSize(interviewPageInfo.getSize());
        mapPageInfo.setTotal(interviewPageInfo.getTotal());
        mapPageInfo.setPages(interviewPageInfo.getPages());
        mapPageInfo.setPrePage(interviewPageInfo.getPrePage());
        mapPageInfo.setNextPage(interviewPageInfo.getNextPage());
        mapPageInfo.setIsFirstPage(interviewPageInfo.isIsFirstPage());
        mapPageInfo.setIsLastPage(interviewPageInfo.isIsLastPage());
        mapPageInfo.setNavigatePages(interviewPageInfo.getNavigatePages());
        mapPageInfo.setNavigatepageNums(interviewPageInfo.getNavigatepageNums());

        // 转换面试数据
        List<Map<String, Object>> mapList = new ArrayList<>();
        for (Interview interview : interviewPageInfo.getList()) {
            mapList.add(convertInterviewToMap(interview));
        }

        mapPageInfo.setList(mapList);
        return mapPageInfo;
    }

    /**
     * 将Interview对象转换为Map结构
     */
    private Map<String, Object> convertInterviewToMap(Interview interview) {
        Map<String, Object> interviewMap = new HashMap<>();
        interviewMap.put("id", interview.getId());
        interviewMap.put("applicationId", interview.getApplicationId());
        interviewMap.put("enterpriseId", interview.getEnterpriseId());
        interviewMap.put("studentId", interview.getStudentId());
        interviewMap.put("positionId", interview.getPositionId());
        interviewMap.put("inviteTime", interview.getInviteTime());
        interviewMap.put("interviewTime", interview.getInterviewTime());
        interviewMap.put("interviewLocation", interview.getInterviewLocation());
        interviewMap.put("status", interview.getStatus() != null ? interview.getStatus().name() : null);
        interviewMap.put("remark", interview.getRemark());
        
        // 关联表信息，只有非空时才放入
        if (interview.getEnterpriseName() != null) {
            interviewMap.put("enterpriseName", interview.getEnterpriseName());
        }
        if (interview.getStudentName() != null) {
            interviewMap.put("studentName", interview.getStudentName());
        }
        if (interview.getPositionName() != null) {
            interviewMap.put("positionName", interview.getPositionName());
        }
        
        return interviewMap;
    }

    /**
     * 构建错误结果
     */
    private Map<String, Object> createErrorResult(String message) {
        Map<String, Object> result = new HashMap<>();
        result.put("code", 500);
        result.put("message", message);
        return result;
    }
}
